package com.kzw.oa.byxt.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kzw.core.service.hibernate.DefaultEntityManager;
import com.kzw.oa.byxt.model.Subject;
import com.kzw.oa.byxt.model.YuXuan;
import com.kzw.oa.model.system.AppUser;

@Service
@Transactional
public class SubjectService extends DefaultEntityManager<Subject, Long> {
	
	@Autowired
	private YuXuanService yuXuanService;

	/**
	 * 将选题指派出某一个学生时：
	 * 		该学生修改某状态
	 * 		该学生其它预选题目删除，并更新其他老师的预选数量
	 * */
	public void saveStudent(AppUser student, Subject subject) {
		
		// 一个题目有很多的预选
		String hql = "from YuXuan x left join fetch x.student where x.subject=?";
		List<YuXuan> list = yuXuanService.findByHQL(hql, subject);
		
		for(YuXuan yx : list) {
			if(yx.getStudent().getUserId().equals(student.getUserId())) {
				// 预选成功, 确定学生的最终题目和选题的信息
				yx.setStatus(3);
				yuXuanService.saveOrUpdate(yx);
				
				subject.setXscnt(1);
				subject.setStudent(student);
				subject.setStatus(5);
				saveOrUpdate(subject);
				
				// 该学生预选的所有题目，都需要更新当前的预选数
				String hql1 = "select x.subject from YuXuan x where x.oid<>? and x.student=?";
				List<Subject> subjects = findByHQL(hql1, yx.getOid(), student);
				
				// 删除该学生的其它预选
				String hql2 = "delete from YuXuan where oid<>? and student=?";
				getEntityDao().batchExecute(hql2, yx.getOid(), student);
				
				// 更新其他老师题目的预选数
				String hql3 = "select count(*) from YuXuan where subject=?";
				for(Subject sub : subjects) {
					Long cnt = findUniqueByHQL(hql3, sub);
					sub.setXscnt(Integer.parseInt(cnt+""));
					saveOrUpdate(sub);
				}
			} else {
				// 其他学生，预选失败，【不能删除】
				yx.setStatus(4);
				yuXuanService.saveOrUpdate(yx);
			}
		}
		
	}

}
